package ms.platform.system.controller;

import ms.platform.email.ExchangeMailService;
import ms.platform.email.MailService;
import ms.platform.system.model.Admin;
import ms.platform.system.model.Menu;
import ms.platform.system.service.AdminService;
import ms.platform.system.service.IndexService;
import ms.platform.system.service.ResourceService;
import ms.platform.system.service.RoleService;
import ms.platform.util.SHAUtil;
import ms.platform.util.StringUtil;
import ms.platform.util.Verificationcode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

@Controller
@RequestMapping("/")
public class IndexController extends BaseController {
    @Autowired
    private IndexService indexService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private MailService mailService;
    @Autowired
    private ExchangeMailService exchangeMailService;
    
    private Logger logger = LoggerFactory
            .getLogger(IndexController.class);

    @RequestMapping(value = "/login")
    public String toLogin(HttpServletRequest request) {
        request.getSession().invalidate();
        return "login";
    }

    @RequestMapping(value = "/index")
    public String toIndex(HttpServletRequest request) {
        String adminId = (String) request.getSession().getAttribute("admin");
        if (adminId == null) {
            return "redirect:/login";
        }
        //admin
        Admin admin = indexService.getAdminById(Integer.valueOf(adminId));
        request.setAttribute("admin", admin);
        //menu
        List<Menu> menuList = resourceService.getAllMenuByAdminId(Integer.valueOf(adminId));
        //arrange the menu
        List<Menu> root = new ArrayList<Menu>();
        if (menuList != null && menuList.size() > 0) {
            for (int i = 0; i < menuList.size(); i++) {
                Menu menu = menuList.get(i);
                for (int j = i + 1; j < menuList.size(); j++) {
                    if (menuList.get(j).getLevel().intValue() == (menu.getLevel() + 1) && menu.getId().equals(menuList.get(j).getParentId().intValue())) {
                        menu.getChildren().add(menuList.get(j));
                        ;
                    }
                }
            }
            for (Menu menu : menuList) {
                if (menu.getLevel() == 1) {
                    root.add(menu);
                } else {
                    break;
                }
            }
        }
        request.setAttribute("menuList", root);
        return "index";
    }

    @RequestMapping(value = "/")
    public String index() {
        return "redirect:/index";
    }

    @RequestMapping(value = "/menu")
    public String toMenu() {
        return "menu";
    }

    @RequestMapping(value = "/main")
    public String toMain() {
        return "main";
    }

    @RequestMapping(value = "/head")
    public String toHead() {
        return "head";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        //return returnSuccess("退出成功！", null);
        return "forward:/login";
    }

    @RequestMapping(value = "/checkLogin")
    public String checkLogin(Admin admin, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
    	String validateCode = (String) request.getSession().getAttribute("checkcode");
    	if(null != admin.getCode()){
    		if(admin.getCode().equalsIgnoreCase(validateCode)){
        		Admin user = indexService.login(admin.getUsername());
                if (user != null) {
                    if (0 == user.getIsUsed()) {
                        request.setAttribute("error", "该用户已禁用");
                        return "forward:/login";
                    } else if (!user.getPassword().equals(SHAUtil.SHA256(admin.getPassword())) && SHAUtil.SHA256(admin.getPassword()) != null) {
                        request.setAttribute("username", admin.getUsername());
                        request.setAttribute("passw", admin.getPassword());
                        request.setAttribute("error1", "用户名或密码有误，请重新输入");
                        return "forward:/login";
                    } else {
                        request.getSession().setAttribute("admin", user.getId().toString());
                        request.getSession().setAttribute("adminUser", user);
                        HashSet<String> resourceList = resourceService.getAllResourceUrlByAdminId(user.getId());
                        request.getSession().setAttribute("admin_resource", resourceList);
                    }
                } else if (admin.getUsername() != null) {
                    if (!StringUtil.isNotNullOrBlock(admin.getUsername())) {
                        request.setAttribute("error", "请输入用户名!");
                    } else {
                        request.setAttribute("error", "用户名或密码有误，请重新输入");
                        request.setAttribute("passw", admin.getPassword());
                        request.setAttribute("username", admin.getUsername());
                    }
                    return "forward:/login";
                }
        	}else{
                request.setAttribute("username", admin.getUsername());
                request.setAttribute("passw", admin.getPassword());
        		request.setAttribute("error", "验证码错误!");
        		return "forward:/login";
        	}
    	}else{
    		request.setAttribute("error", "请填写验证码!");
    		return "forward:/login";
    	}
        return "redirect:/index";
    }

    @RequestMapping(value = "/findPassword")
    public @ResponseBody
    Map<String, Object> findPassword(Admin admin, HttpServletRequest request) throws Exception {
        Admin user = indexService.login(admin.getUsername());
        Map<String, Object> mapSystem = new HashMap<String, Object>();
        if (user != null) {
            if (0 == user.getIsUsed()) {
                mapSystem.put("infoss", "1");
                return mapSystem;
            } else {
                //对比是否是注册邮箱
                if (!admin.getEmail().equals(user.getEmail())) {
                    mapSystem.put("infoss", "2");
                    return mapSystem;
                }
                //进行修改密码
                String pas = generatePassword();
                admin.setId(user.getId());
                admin.setPassword(SHAUtil.SHA256(pas));
                try {
                    adminService.update(admin);

                    //进行发送邮件
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                    String date = df.format(new Date());
                    exchangeMailService.send("密码找回", new String[]{admin.getEmail()}, null, "亲爱的用户：\n" +
                            "您好！\n" +
                            "您在" + date + "提交了重置密码请求。\n" +
                            "您已经成功重置密码了！密码为： " + pas + "  \n" +
                            "为了您的帐号安全，请尽快重新设置登录密码,并注意以下几点：\n" +
                            "① 密码不要设置过于简单，像123456、000000、123123这类过于简单的密码很容易被猜到导致帐号被盗；\n" +
                            "② 尽量设置没有规律但自己容易记住的数字字母组合作为密码，密码长度可以根据自己方便记忆设置；\n" +
                            "③ 密码作为私密的信息请勿泄露给其他人，以免帐号被盗造成不必要的损失");
                    mapSystem.put("infoss", "4");
                } catch (Exception e) {
                    logger.error(e.getMessage());
                }
                return mapSystem;
            }
        } else if (admin.getUsername() != null) {
            mapSystem.put("infoss", "3");
            return mapSystem;
        }
        return mapSystem;
    }

    public static String generatePassword() {
        String[] pa = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
                "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
        StringBuffer sb = new StringBuffer("");
        for (int i = 0; i < 6; i++) {
            sb.append(pa[(Double.valueOf(Math.random() * pa.length).intValue())]);
        }
        String[] spe = {"`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "=", "+", "[", "]", "{", "}", "\\", "/", "?", ",", ".", "<", ">"};
        sb.append(spe[(Double.valueOf(Math.random() * spe.length).intValue())]);
        sb.append((int) (Math.random() * 100));
        return sb.toString();
    }

    /**
	 * 生成四位随机数字
	 * @param request
	 * @return
	 */
	@RequestMapping("/verifcationCode")
    public void saveProgressDetail(HttpServletRequest request,HttpServletResponse response){
        try {
            BufferedImage image = this.createCheckPic(request);
            OutputStream out = response.getOutputStream();
            ImageIO.write(image, "JPEG", out);
            out.close();
        } catch (Exception e) {
            System.out.println("验证码生成异常:"+ e);
        }
    }

    public BufferedImage createCheckPic(HttpServletRequest request) {
        //
		/*
		 * 得到参数高，宽，都为数字时，则使用设置高宽，否则使用默认值
		 */
        int w = 75;
        int h = 32;

        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

		/*
		 * 生成背景
		 */
        Verificationcode.createBackground(g,w,h);

		/*
		 * 生成字符
		 */
        String s = Verificationcode.createCharacter(g);
        request.getSession().setAttribute(Verificationcode.VALIDATE_CODE, s);
        g.dispose();
        return image;
    }
}



